<?php
namespace ESTool;
/**
 * API辅助处理工具类
 */
class Debug {
	static $_show_memory;
	static public $memory_using = array("start");
	static public $display_ini = '';
	static public function op_memory_set_sql() {
	    if (!self::op_display_error()) {
	        return true;
	    }
	    $args = func_get_args();
	    // $pos = json_encode($args);
	    list( $usec ,  $sec ) =  explode ( " " ,  microtime ());
	
	    self::$memory_using[] = array(
	        'debug_pos' => $args,
	        'type' => 'sql',
	        'using_stat' => self::convert(memory_get_usage(true)),
	        'ctime' => date("H:i:s") . " - " . ((float) $usec  + (float) $sec )
	    );
	    return true;
	}
	static public function op_memory_set_query() {
		if (!self::op_display_error()) {
			return true;
		}
		$args = func_get_args();
		// $pos = json_encode($args);
		
		self::$memory_using[] = array(
			'debug_pos' => $args,
		    'type' => 'query',
			'using_stat' => self::convert(memory_get_usage(true)),
			'ctime' => date("H:i:s") . " - " . self::current_microtime()
		);
		return true;
	}
	/**
	 * 记录当前数据，埋入测试点
	 * @param string $file  文件__FILE__
	 * @param string $line  行数__LINE__
	 * @param string $tag    标记（唯一）
	 * @return boolean
	 */
	static public function op_memory_set() {
		if (!self::op_display_error()) {
			return true;
		}
		$args = func_get_args();
		// $pos = json_encode($args);
		list( $usec ,  $sec ) =  explode ( " " ,  microtime ());
		
		
		$ver = 0;
		// 唯一标识key, 每两个为一组，多出来的连接 版本
		$key = trim($args[2]);
		while (isset(self::$memory_using[$key]['over_stat'])) {
		    $ver++;
		    $key = trim($args[2]) . "-" . $ver;
		}
		$args[2] = $key;
		$item = array(
		    'debug_pos' => $args,
		    'using_stat' => self::convert(memory_get_usage(true)),
		    'ctime' => date("H:i:s") . " - " . self::current_microtime(),
		    'microtime' => self::current_microtime(),
		    'memory' => memory_get_usage(true),
		);
		if (isset(self::$memory_using[$key])) {
		    $item['over_stat'] = self::convert($item['memory'] - self::$memory_using[$key]['memory']);
		    $item['over_time'] = $item['microtime'] - self::$memory_using[$key]['microtime'];
		}
		
	    self::$memory_using[$key] = $item;
		
		return true;
	}
	static public function current_microtime() {
	    list( $usec ,  $sec ) =  explode ( " " ,  microtime ());
	    return ((float) $usec  + (float) $sec );
	}
	/**
	 * 输出内存记录
	 * @param int $print_level 打印最后N个内存记录
	 * @param bool $print_all 输出全部记录
	 */
	static public function op_memory($print_level=1, $print_all=false) {
		if (!self::op_display_error()) {
			return true;
		}
		if ($print_all == false) {
			$curr_pos = count(self::$memory_using) - 1;
			$result[] = array(
				'curr_pos' => $curr_pos,
				'curr_data' => end(self::$memory_using)
			);
			while ($curr_pos) {
				next(self::$memory_using);
				$curr_pos = key(self::$memory_using);
				$result[] = array(
					'curr_pos' => $curr_pos,
					'curr_data' => current(self::$memory_using)
				);
			}
		} else {
			$result = array(
				'curr_pos' => 'all',
				'curr_data' => self::$memory_using
			);
		}
		return Debug::op_dump($result);
	}
	/**
	 * OP后台输调试信息
	 */
	static public function op_dump(){
		if (!self::op_display_error()) {
			return true;
		}
		
		header("Content-type:text/html;charset=utf-8");
		$args = func_get_args(); // 获取多个参数
		
		$header = '<div style="text-align: left; white-space: pre-line; line-height: 30px; 
                font-weight: 600; font-size: 16px; color: rgb(51, 51, 51); 
                background: rgb(238, 238, 238) none repeat scroll 0px 0px; 
                border-radius: 10px; padding: 10px; width: 90%; margin: 15px;"><pre>';
		$footer = '</pre></div>';
		$root = substr($_SERVER['DOCUMENT_ROOT'], 0 , strlen($_SERVER['DOCUMENT_ROOT']) - strlen('application/'));
		$root = str_replace("/", "\\", $root);
		// 多个参数循环输出
		foreach ($args as $arg) {
			if (is_array($arg) || is_object($arg)) {
				// var_export($arg['curr_data']);exit;
				foreach ($arg['curr_data'] as $key => $item) {
				    $type = isset($item['type']) ? $item['type'] : "Debug";
				    isset($result[$type]) || $result[$type] = array();
				    if (is_array($item)) {
				        $result[$type][$key]['current_time'] = sprintf("当前时间:%s", $item['ctime']);
				        $result[$type][$key]['over_time'] = sprintf("消耗时间:%f", $item['over_time']);
				        $result[$type][$key]['memory_over'] = sprintf("所用内存:%s", $item['using_stat']);
				        $result[$type][$key]['over_stat'] = sprintf("消耗内存:%s", $item['over_stat']);
				        
				        foreach ($item['debug_pos'] as $k => $v) {
				            if (is_array($v)) {
				                foreach ($v as $vv) {
    				                if (strstr($vv, $root) !== false) {
    				                    $result[$type][$key]['file'] = sprintf("文件:%s ", $vv);
    				                } elseif (is_numeric($vv)) {
    				                    $result[$type][$key]['line'] = sprintf("行:%d", $vv);
    				                } else {
    				                    $result[$type][$key]['tag'][] = sprintf("标记:%s", $vv);
    				                }
				                }
				            } else {
    				            $v = str_replace("/", "\\", $v);
    				            if (strstr($v, $root) !== false) {
    				                $result[$type][$key]['file'] = sprintf("文件:%s ", $v); 
    				            } elseif (is_numeric($v)) {
    				                $result[$type][$key]['line'] = sprintf("行:%d", $v);
    				            } else {
    				                $result[$type][$key]['tag'][] = sprintf("标记:%s", $v);
    				            }
				            }
				           
				        }
				    }
				}
			} else {
				var_dump($arg);
			}
		}
		$debug = "";
		foreach ($result as $type => $list) {
		    $body = '';
		    foreach ($list as $str) {
    		    $str['tag'] = implode("\n", $str['tag']). "\n";
    		    $body .= implode("\n", $str). "\n" ;
		    }
		    empty($type) && $type = 'Debug';
		    $debug .= "<h1>".strtoupper($type)."</h1>".$header . "开始输出Debug信息：\n" . "\n". $body . $footer;
		}
		echo $debug;
        return $result;		
	}

	/**
	 * mysql 调试开关
	 */
	static public function op_display_error() {
		$display_where_1 = false;
		$display_where_1 = $display_where_1 || isset($_GET['debug_stat']);
		//$display_where_2 = strstr(strtolower($_SERVER["HTTP_HOST"]), 'op1.esf.sina.com.cn') !== false;
		$display_where_2 = true;
		if ($display_where_1 && $display_where_2) {
			if (empty(self::$display_ini)) {
				// ini_set('display_errors', 'On');
				// error_reporting(E_ALL);
				self::$display_ini = 'On';
			}
			return true;
		} else {
			return false;
		}
	}
	/**
	 * mysql 调试开关 
	 */
	static public function op_mysql_debug($open=false) {
		if (!self::op_display_error()) {
			return true;
		}
		self::$_show_memory = true;
		return true;
	}
	static public function convert($size) {
		$unit=array('b','kb','mb','gb','tb','pb');
		return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
	}
}